#pragma once

#include "log.hpp"
#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include "protocol.hpp"

enum{
    SOCKERROR = 1,
    BINDERROR,
    LISTENERROR
};

class tcpServer{
public:
    tcpServer(const uint16_t& port) :_listen_sock(-1),_port(port) 
    {}
    struct tcpserverdata{
        tcpserverdata(tcpServer* tthis,const int& sockfd)
            :_this(tthis),_sockfd(sockfd)
        {}
        tcpServer* _this;
        int _sockfd;
    };

    void initServer(){
        //创建套接字
        _listen_sock = socket(AF_INET,SOCK_STREAM,0);
        if(_listen_sock == -1){
            logmessage(FATAL,"socket filed!");
            exit(SOCKERROR);
        }else logmessage(NORMAL,"socket success");
        //bind
        sockaddr_in local;
        socklen_t len = sizeof local;
        memset(&local,0,len);
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        local.sin_port = htons(_port);
        if(bind(_listen_sock,(sockaddr*)&local,len) == -1){
            logmessage(FATAL,"bind filed!");
            exit(BINDERROR);
        }
        logmessage(NORMAL,"bind succuss");
        //将sock设置为监听
        if(listen(_listen_sock,5) == -1){
            logmessage(FATAL,"listen filed!");
            exit(LISTENERROR);
        }
        logmessage(NORMAL,"listen succuss");
    }
    // static void Communication(int communication_fd){
    // #define MAXBUFFER 1024
    //     //接收消
    //     while(true){
            
    //         char messega[MAXBUFFER];
    //         ssize_t s = read(communication_fd,messega,MAXBUFFER);
    //         if(s >0){
    //             messega[s] = 0;
    //             std::cout<<messega<<std::endl;
    //             //std::cout<<"jie shou cg"<<std::endl;
    //             std::string retmessage(messega);
    //             retmessage += "[server echo]";
    
    //             ssize_t r = write(communication_fd,retmessage.c_str(),retmessage.size());
    //             if(r == -1){
    //                 logmessage(ERROR,"write filed");
    //             }
    //         }else if(s == 0){
    //             logmessage(ERROR,"client close");
    //             break;
    //         }
        
    //     }
    // }
    // static void* threadroutine(void* args){
    //     tcpserverdata* info = static_cast<tcpserverdata*>(args);
    //     info->_this->Communication(info->_sockfd);//完成通信
    //     close(info->_sockfd);
    //     delete(info);
    // }
    //协议 "textlen/r/ntext"
    #define INBUFFERMAX 1024
    void getcompletemessage(int sockfd,std::string& message,std::string& testout){
        while(true){
            char buffer[INBUFFERMAX] ={0};
            ssize_t s = recv(sockfd,buffer,INBUFFERMAX-1,0);
            if(s > 0){
                buffer[s] = 0;
                message+=buffer;
                std::cout<<"接收到的完整数据是"<<message<<std::endl;
                auto pos = message.find(SEP);
                if(pos == message.npos){
                    std::cout<<"接收报头不完整，重新接收"<<std::endl;
                    continue;
                }
                std::string len_str = message.substr(0,pos);
                int len = std::atoi(len_str.c_str());
                std::cout<<"接收到的报头是:"<<len<<std::endl;
                if(message.size()-len_str.size()-SEPLEN < len){
                    std::cout<<"接收数据不完整，重新接收数据"<<std::endl;
                    continue;
                }
                testout = message.substr(0,len+len_str.size()+SEPLEN);
                std::cout<<"接收数据完整"<<testout<<std::endl;
                message.erase(0,pos+SEPLEN+len);
                std::cout<<"剩余数据"<<message<<std::endl;
                break;
            }
        }
    }


    void Communication(int sockfd){
        //1.接收完整报文
        std::string message;
        while(true)
        {
            std::string test;//完整报文
            getcompletemessage(sockfd,message,test);
            //1.1先读到一个！完整报文
            
            //1.2去除报头
            std::string s = deleteheader(test);
            std::cout<<"去除包头后是"<<s<<std::endl;
            //2.对请求到的Request反序列化
            Request req;
            req.unserialization(s);
            Response res;
            //3.业务处理
            handler(req,res);
    
            //4.将response序列化
            std::string r;
            res.serialization(&r);
            std::cout<<"序列化"<<r<<std::cout;
            //5.发送报文
            //5.1添加报头
            std::cout<<"------"<<std::endl;
            std::string sendtest = addheader(r);
            std::cout<<"发送数据"<<sendtest<<std::endl;
            //5.2发送完整报文
            size_t sendr = send(sockfd,sendtest.c_str(),sendtest.size(),0);
            if(sendr == 0) break;
        }
    }

    void start(){
        for( ; ; ){
            //建立链接
            sockaddr_in remote;
            socklen_t len = sizeof remote;
            memset(&remote,0,len);
            int commfd = accept(_listen_sock,(sockaddr*)&remote,&len);
            if(commfd == -1){
                logmessage(ERROR,"accept filed!");
                continue;
            }
            logmessage(NORMAL,"accept succuss,sockfd:%d",commfd);
            //std::cout<<"sockfd:"<<commfd<<std::endl;
            //进行通信
            //多进程版本:
            pid_t id = fork();
            if(id == 0){
                if(fork()!= 0)  exit(0);
                Communication(commfd);//孤儿孙子进程执行通信逻辑
                exit(0);
            }
            //关闭通信接口
            close(commfd); //父进程已经不需要通信，孙子进程已经继承了通信接口了
            pid_t ret = waitpid(id,nullptr,0);
            std::cout<<"wait succuss:"<<ret<<std::endl;
            //多线程版本:
            // pthread_t tid;
            // tcpserverdata* info = new tcpserverdata(this,commfd);
            // int ret = pthread_create(&tid,nullptr,threadroutine,info);
            // pthread_detach(tid);
            //线程池版本:
            //构建任务
        }
    }

    ~tcpServer(){
        close(_listen_sock);
    }

private:
    int _listen_sock;
    uint16_t _port;
};